package edu.kaist.cs408.pof.backend.dao;

import com.google.code.morphia.query.Query;
import com.google.code.morphia.query.UpdateOperations;
import edu.kaist.cs408.pof.common.model.DishVo;
import edu.kaist.cs408.pof.common.model.RestaurantVo;
import org.apache.log4j.Logger;
import org.bson.types.ObjectId;
import org.springframework.context.annotation.Configuration;

import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: duyleekun
 * Date: 5/9/12
 * Time: 8:25 PM
 * To change this template use File | Settings | File Templates.
 */
@Configuration
public class RestaurantDaoImpl extends DaoBase {

	static Logger log = Logger.getLogger(RestaurantDaoImpl.class);

	public RestaurantVo createRestaurant(RestaurantVo newRestaurant) {
		datastore.save(newRestaurant);
		return newRestaurant;
	}


	public List<RestaurantVo> getRestaurants(boolean openStatus) {
		return datastore.find(RestaurantVo.class, "openStatus", openStatus).asList();
	}


	public List<RestaurantVo> getRestaurants() {
		return datastore.find(RestaurantVo.class).asList();
	}


	public RestaurantVo addDish(ObjectId restaurant, ObjectId dish) {
		Query<DishVo> findDishOp = datastore.find(DishVo.class, "_id", dish);
		Query<RestaurantVo> findRestOp = datastore.find(RestaurantVo.class, "_id", restaurant);

		UpdateOperations<RestaurantVo> addDishOp = datastore.createUpdateOperations(RestaurantVo.class).add("dishes", findDishOp.getKey());

		return datastore.findAndModify(findRestOp, addDishOp);
	}

	public RestaurantVo rate(ObjectId restaurant, int score) {
		Query<RestaurantVo> findRestOp = datastore.find(RestaurantVo.class, "_id", restaurant);
		UpdateOperations<RestaurantVo> voteOp = datastore.createUpdateOperations(RestaurantVo.class).inc("countReview", score).inc("totalReviewScore", 1);

		return datastore.findAndModify(findRestOp, voteOp);
	}

	public RestaurantVo get(ObjectId restaurant) {
		return datastore.get(RestaurantVo.class, restaurant);
	}
}
